package org.sgy.mall.connection;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

public class DataSource {
	private static BasicDataSource datasource = null;

	public static void init() {
		if (datasource != null) {
			try {
				datasource.close();
			} catch (Exception e) {
			}
			datasource = null;
		}
		try {
			Properties properties = new Properties();
			// 必须
			properties.setProperty("driverClassName", "com.mysql.jdbc.Driver");
			properties.setProperty("url", "jdbc:mysql://localhost:3306/edmall?characterEncoding=utf-8");
			properties.setProperty("username", "root");
			properties.setProperty("password", "root");
			properties.setProperty("maxActive", "30");
			// 默认
			properties.setProperty("maxIdle", "10");
			properties.setProperty("maxWait", "1000");
			properties.setProperty("removeAbonded", "false");
			properties.setProperty("removeAbondedTimeout", "120");
			properties.setProperty("testOnBorrow", "true");
			properties.setProperty("logAbandoned", "true");
			// 创建数据库
			datasource = (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {

		}
	}

	public static synchronized Connection getConnection() throws SQLException {
		if (datasource == null) {
			init();
		}
		Connection connection = datasource.getConnection();
		return connection;
	}
}
